package com.lailai.exception;

import com.lailai.constant.ErrorCode;
import com.lailai.domainservice.response.SingleResponse;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

// 统一处理参数校验异常
@RestControllerAdvice
public class ValidationExceptionHandler {
    // 参数校验异常处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public SingleResponse<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        List<FieldError> errors = ex.getBindingResult().getFieldErrors();
        StringBuilder errorMsg = new StringBuilder();
        for (FieldError error : errors) {
            errorMsg.append(error.getField()).append(": ").append(error.getDefaultMessage()).append("; ");
        }
        return SingleResponse.ofFailure(
                String.valueOf(ErrorCode.PARAMETER_ERROR.getCode()),
                errorMsg.toString()
        );
    }
}
